const Model = require('@/models')

class XmindModel extends Model {
  async findPage ({ pageNo, pageSize, conditions }) {
    const conditionSql = this.generateWhereClauseOR(conditions)
    const sql = `select x_mind.id, x_mind.name, x_mind.cover, x_mind.recommend, x_mind.createTime, x_mind.updateTime, x_mind.userId, user.nickname from x_mind
    left join user on user.id = x_mind.userId ${conditionSql} 
    order by x_mind.createTime desc limit ${pageSize} offset ${(pageNo - 1) * pageSize}`
    try {
      const list = await this.db.query(sql)
      const total = await this.total(conditionSql)
      return {
        list,
        total
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  async total (conditionSql) {
    const sql = `select count(*) as total from x_mind left join user on user.id = x_mind.userId ${conditionSql}`
    try {
      const total = await this.db.query(sql)
      return total[0].total
    } catch (error) {
      throw new Error(error)
    }
  }

  async updateRecommend (xmindId, recommend) {
    const sql = 'update x_mind set recommend = ? where id = ?'
    try {
      await this.db.query(sql, [recommend, xmindId])
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new XmindModel('x_mind')
